﻿using MediatR;
using SmartCity.ProcessEngine.API.Read.Application.Commands.Forms;
using SmartCity.ProcessEngine.API.Read.DTO;
using SmartCity.ProcessEngine.Domain;
using SmartCity.ProcessEngine.Errorcode;
using SmartCity.ProcessEngine.Infrastructure.Interfaces;

namespace SmartCity.ProcessEngine.API.Read.Application.CommandHandlers.Forms
{
    public class FormQueryCommandHandler : IRequestHandler<FormQueryCommand, ApiResult<List<FormDto>>>
    {
        private readonly IBaseRepository<WF_Form> formRep;
        private readonly IBaseRepository<WF_FromType> typeRep;
        private readonly IBaseRepository<Industry> industryRep;

        public FormQueryCommandHandler(IBaseRepository<WF_Form> formRep,IBaseRepository<WF_FromType> typeRep,IBaseRepository<Industry> industryRep)
        {
            this.formRep = formRep;
            this.typeRep = typeRep;
            this.industryRep = industryRep;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回表单集合任务</returns>
        public Task<ApiResult<List<FormDto>>> Handle(FormQueryCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<FormDto>> result = new ApiResult<List<FormDto>>();
            result.code = ApiEnum.SearchSuccess;
            result.message = "成功";

            var list = from a in formRep.GetAll()
                       join b in typeRep.GetAll()
                       on a.TypeNo equals b.TypeNo
                       join c in industryRep.GetAll()
                       on b.IndustryId equals c.IndustryId
                       where !a.IsDeleted
                       select new FormDto
                       {
                           FormId = a.FormId,
                           FormNo = a.FormNo,
                           FormName = a.FormName,
                           FormDesc = a.FormDesc,
                           TypeNo = b.TypeNo,
                           TypeName = b.TypeName,
                           IndustryId = c.IndustryId,
                           IndustryName = c.IndustryName,
                           IsDeleted = a.IsDeleted,
                       };
            if(request.IndustryId > 0)
            {
                list = list.Where(x=>x.IndustryId == request.IndustryId);
            }
            if(!string.IsNullOrEmpty(request.TypeNo))
            {
                list = list.Where(x=>x.TypeNo == request.TypeNo);
            }
            if(!string.IsNullOrEmpty(request.FormName))
            {
                list = list.Where(x => x.FormName == request.FormName);
            }

            result.data = list.ToList();

            return Task.FromResult(result);
        }
    }
}
